/*
 * @Author: zhangzhengzhe
 * @Date: 2019-09-02 16:23:37
 * @LastEditors: zhangzhengzhe
 * @LastEditTime: 2019-09-05 13:11:56
 */

const mongoose = require('mongoose')
const UserModel = require('../module/user')
const db = require('./../utils/db')
module.exports = {
  login: async (ctx, next) => {
    try {
      const { username, password } = ctx.request.body
      const files = ctx.request.files
      // const bufferFile = new Buffer()
      const bufferFile = Buffer.from(files.file.path)
      const userInfo = Object.assign({}, ctx.request.body, { files: bufferFile })
      const res = null
      // console.log(files)
      if (!username || !password || !files) {
        ctx.body = {
          code: 0,
          message: '请输入账号或密码...',
          data: userInfo
        }
      } else {
        if (username !== '' && password !== '' && userInfo.files !== '') {
          const User = await UserModel(userInfo)
          const userResult = new User(userInfo) // 设置数据模型
          // 保存数据到数据库  save 更新数据时，若数据存在，则覆盖 insert更新数据时，若数据存在，则抛出异常
          // if(db.users.find({'username': username})) {
          //   res = await userResult.find('')
          // } else {
            console.log(db.getCollection('zzz_user_infos').find({username: 'zzz123'}))
            res = await userResult.save(userResult)
          // }
          // const res =await db.users.insert(ctx.request.body)
          ctx.body = {
            code: 200,
            message: '登录成功',
            data: res
          }
        } else {
          ctx.body = {
            code: 0,
            message: '账号或者密码不能为空',
            data: userInfo
          }
          // throw new Error('账号或者密码不能为空......')
        }
      }
    } catch (error) {
      // console.log(error)
      if(error) {
        ctx.body = {
          code: 1001,
          message: '注册失败',
          data: {}
        }
      } else {
        ctx.body = {
          code: 500,
          message: "服务器错误",
          data: {}
        }
      }
    }
  }
}